package com.aaa.bookproject.config;

import com.aaa.bookproject.util.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * 自定义前后端分离的拦截器,
 * 并将此拦截器添加到ShiroConfig配置类中
 * @author ：YongQi Lv
 * @date ：2021/4/26 14:08
 */
public class LoginFilter extends FormAuthenticationFilter {

    /**
     * 用户没有登录的时候，默认走的方法
     * Access 通道   Denied 拒绝
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        ResultData resultData = new ResultData();
        ObjectMapper mapper = new ObjectMapper();
        // 返回给前端的数据
        resultData.setCode(400);
        resultData.setMsg("未登录不可访问");
        // 类型转换
        HttpServletResponse resp = (HttpServletResponse) response;
        // 设置字符集
        resp.setCharacterEncoding("UTF-8");
        // 转换为json字符串
        String data = mapper.writeValueAsString(resultData);
        resp.getWriter().write(data);
        // 关闭
        return false;
    }
}
